// api.js
import { DatasetAPI, LabeldataAPI, AutolabelAPI } from './cloud';
import { LocalAPI } from './local';
import { RemoteAPI } from './remote';
import { AsyncTaskPoller } from '../utils/pollingUtils';

class API {
    constructor() {
        this.local = new LocalAPI();
        this.remotes = new RemoteAPI();
        this.cloud = {
            dataset: new DatasetAPI(),
            labeldata: new LabeldataAPI(),
            autolabel: new AutolabelAPI()
        };

        this.provider = 'local';
        this.remoteId = -1;

        // 异步任务轮训器
        this.poller = new AsyncTaskPoller(this);
    }

    // 设置API的提供者
    async setProvider(provider) {
        const regex = /^remote:(\d+)$/;
        const match = regex.exec(provider);

        if (match) {
            this.provider = 'remote';
            this.remoteId = parseInt(match[1], 10);
            // console.log(`this.remoteId = ${this.remoteId}`);
            await this.remotes.setRemoteId(this.remoteId);
        } else {
            if (provider == 'local' || provider == 'cloud') {
                this.provider = provider;
                this.remoteId = -1;
            }
        }
    }

    getProvider() {
        if (this.provider == 'local') {
            return 'Local';
        } else {
            return 'Remote:' + this.remotes.remoteName;
        }
    }

    api_url(method, params) {
        if (this.provider == 'local') {
            return this.local.api_url(method, params);
        } else if (this.provider == 'remote') {
            return this.remotes.api_url(method, params);
        }
    }

    // 调用API，如果callback赋值，则API是异步方式，轮训获取对应的状态
    async invoke(method, params, callback, pollingTime = 1000) {
        let result = null;

        // Invoke local or remote method
        try {
            if (this.provider == 'local') {
                result = await this.local.invoke(method, params);
            } else if (this.provider == 'remote') {
                result = await this.remotes.invoke(method, params);
            }
        } catch (error) {
            return { code: -1, msg: 'Error during initial invoke.' };
        }

        // If callback is defined and the method succeeded
        if (callback && result.code === 0 && result.msg && result.msg.method === 'async') {
            this.asyncTaskPolling(result.msg.task_id, callback, pollingTime);
        }
        return result;
    }

    // 封装异步状态轮询函数
    async asyncTaskPolling(taskId, callback, pollingTime = 1000, provider = null, clearByTheEnd = false) {
        console.log('asynTaskPolling taskId = ', taskId);
        await this.poller.asyncTaskPolling(taskId, callback, pollingTime, provider, clearByTheEnd);
    }

    // 停止异步状态轮训函数
    async stopAsyncPolling(taskId) {
        if (taskId) {
            await this.poller.stopPolling(taskId);
        } else {
            await this.poller.stopAllPolling();
        }
    }
}

export default new API();
